<template>
  <v-chart class="chart" :option="option" />
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { graphic } from "echarts/core";

import { ElMessage } from "element-plus";
import { useMapLayerStore } from "@/stores";
import { LayerInfoType } from "@/types";
import { mapLayerEnum } from "@/enums";
import { exportJsonToExcel } from "@/utils";

const mapLayerStore = useMapLayerStore();

let downloadList:
  | Record<string, any>[]
  | { 指标类型: string; 指标数量: number }[] = [];

const download = () => {
  exportJsonToExcel(downloadList, "调研指标统计", "统计结果");
};

const option = computed(() => {
  const currentData = mapLayerStore.currentMapData;
  const currentType = mapLayerStore.mapType;
  const keyObject = {
    [mapLayerEnum.ISSUE]: "issueType",
    [mapLayerEnum.PROJECT]: "projectType",
    [mapLayerEnum.RECTIFICATION]: "rectificationType",
  };
  const data: { [key: string]: number } = {};
  if (currentData.length) {
    currentData.map((item: LayerInfoType) => {
      const typeKey = keyObject[currentType as mapLayerEnum];
      const key = item[typeKey as keyof LayerInfoType];
      if (key !== null && key !== undefined) {
        if (data[key]) {
          data[key]++;
        } else {
          data[key] = 1;
        }
      }
    });
    downloadList = Object.entries(data).map(([key, value]) => {
      return {
        指标类型: key,
        指标数量: value,
      };
    });
    return {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      xAxis: {
        type: "category",
        data: Object.keys(data),
        axisLabel: { color: "#ffffff" },
      },

      yAxis: {
        type: "value",
        axisLabel: { color: "#ffffff" },
        splitLine: {
          lineStyle: { color: "rgba(255,255,255,0.3)" },
        },
      },
      grid: {
        left: "40px",
        right: "20px",
        bottom: "40px",
        top: "20px",
      },
      series: [
        {
          data: Object.values(data),
          type: "bar",
          barWidth: 20,
          itemStyle: {
            color: "#00fdfa",
          },
        },
      ],
    };
  } else {
    return {
      xAxis: {
        type: "category",
        data: [""],
      },
      yAxis: {
        type: "value",
      },
      grid: {
        left: "40px",
        right: "20px",
        bottom: "40px",
        top: "20px",
      },
      series: [
        {
          data: [0],
          type: "bar",
          barWidth: 20,
          itemStyle: {
            color: "#00fdfa",
          },
        },
      ],
    };
  }
});
defineExpose({
  download,
});
</script>

<style scoped lang="scss"></style>
